package com.github.live.plugins.base;

import android.content.res.XmlResourceParser;
import android.util.Log;

import com.github.live.util.LogFactory;
import com.github.livebase.EpgInformationUpdater;
import com.github.livebase.bean.EpgInformation;
import com.github.livebase.database.EpgOperator;
import com.github.livebase.log.LogUtil;
import com.github.livebase.util.base.CollectionsUtil;
import com.github.livebase.util.base.DateUtil;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Set;

/**
 * @ClassName TodayUpdater
 * @description: 只更新当天的信息
 * @author: biao532
 * @create: 2023-12-30 13:23
 * @Version 1.0
 **/
public class TodayUpdater extends EpgInformationUpdater {
    public TodayUpdater(EpgOperator operator, Set<String> channelIdSet) {
        super(operator, channelIdSet);
    }

    @Override
    protected List<EpgInformation> onDateChange(EpgOperator operator, Date date) {
        long time = date.getTime();
        long end = time + 24*3600_000;
        LogFactory.info(TodayUpdater.class, "ready update Epg");
        List<EpgInformation> l = g(DateUtil.format(new SimpleDateFormat("yyyyMMdd"), date), "");
        int delete = operator.delete(time);
        LogFactory.info(TodayUpdater.class, "read epg size={} delete old epg {}", l != null ? l.size():0, delete);

        return CollectionsUtil.filter(l, (e)-> {
            return DateUtil.betweenAnd(e.getStart(), time, end) || DateUtil.betweenAnd(e.getEnd(), time, end);
        });
    }

    private List<EpgInformation> g(String today, String tomorrow) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        try {
            connection = (HttpURLConnection) new URL("http://epg.51zmt.top:8000/e.xml").openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.connect();
            if (200 == connection.getResponseCode()) {
                inputStream = connection.getInputStream();
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                XmlPullParser parser = factory.newPullParser();
                parser.setInput(new InputStreamReader(inputStream));
                return parse2Epg(parser, today, tomorrow);
            }
            LogFactory.info(TodayUpdater.class,  "read epg fail response code is {}", connection.getResponseCode());
        } catch (IOException | XmlPullParserException e) {
            LogFactory.warn(TodayUpdater.class, e, LogUtil.ERROR_OCCURRED,"read epg");
        }
        finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LogFactory.warn(TodayUpdater.class, e, LogUtil.ERROR_OCCURRED, "inputStream");
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return null;
    }

    private List<EpgInformation> parse2Epg(XmlPullParser parser, String today, String tomorrow) {
        List<EpgInformation> list = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss Z", Locale.CHINA);
        try {
            int type = XmlPullParser.END_DOCUMENT;
            while ((type = parser.getEventType()) != XmlPullParser.END_DOCUMENT) {
                if (type == XmlResourceParser.START_TAG) {
                    String name = parser.getName();
                    if (!"programme".equals(name)) {
                        parser.next();
                        continue;
                    }
                    String channelId = parser.getAttributeValue(2);
                    if (!channelIdSet.contains(channelId)) {
                        parser.next();
                        continue;
                    }
                    String start = parser.getAttributeValue(0);
                    if (start== null || (!start.startsWith(today) && !start.startsWith(tomorrow))){
                        parser.next();
                        continue;
                    }
                    String stop = parser.getAttributeValue(1);
                    EpgInformation c = new EpgInformation(channelId, format.parse(start).getTime(), format.parse(stop).getTime());
                    title(parser, c);
                    list.add(c);
                }
                parser.next();
            }
        } catch (XmlPullParserException | IOException | ParseException e) {
            LogFactory.warn(TodayUpdater.class, e, LogUtil.ERROR_OCCURRED, "parse2Epg");
        }
        return list;
    }

    private void title(XmlPullParser parser, EpgInformation information) {
        try {
            int type = XmlPullParser.END_TAG;
            while ((type = parser.getEventType()) != XmlPullParser.END_TAG) {
                if (type == XmlResourceParser.START_TAG) {
                    String name = parser.getName();
                    if (!"title".equals(name)) {
                        parser.next();
                        continue;
                    }
                    String text = parser.nextText();
                    information.setTitle(text);
                }
                parser.next();
            }
        } catch (XmlPullParserException | IOException e) {
            LogFactory.warn(TodayUpdater.class, e, LogUtil.ERROR_OCCURRED, "title");
        }
    }
}
